package com.lyf.gateway.filter;


import com.lyf.common.api.CommonResult;
import com.lyf.common.utils.JacksonUtil;
import com.lyf.gateway.config.InnerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.lyf.gateway.constant.Constant.UNKNOWN;

/**
 * @ClassName InternalFilter
 * @Description: 内网允许访问鉴权
 * 参考： https://www.cnblogs.com/yangzhilong/p/9447905.html
 * @Author kang
 * @Date 2020/12/26 19:39
 * @Version 1.0
 */
@Slf4j
@RefreshScope
@Component
public class InternalFilter implements WebFilter {
    @Autowired
    private InnerConfig innerConfig;
    @Value("${internalFilter.innerIpAddress}")
    private String[] innerIpAddress;
    @Value("${swagger.resource.enable}")
    private boolean enable;
    /**
     * 默认内网, 使用字符串前匹配方式。不严格按32位IP端处理。
     */
    private static final Set<String> INNER_IP = new HashSet<String>() {{
//        10.0.0.0/8, 100.64.0.0/10, 172.16.0.0/12, 192.168.0.0/16, 127.0.0.0/8, 10.123.16.0/20
//        10.0., 100.64., 172.16., 192.168., 127.0., 10.123.
        add("0:0:0:0:0:0:0:1");
    }};

    private static CommonResult forbiddenCommonResult = CommonResult.forbidden(null);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = exchange.getRequest().getURI().getPath();
        String ip = this.getIpAddress(request);
        if (path.contains(innerConfig.getDocPrefix())) {
            log.debug("访问的地址包含了/doc.html：{}", path);
            if (!enable) {
                log.warn("预生产生产环境的网关不能直接访问/doc.html，IP：{}", ip);
                return this.forbidden(response, forbiddenCommonResult);
            }
        }
        return chain.filter(exchange);
    }


    /**
     * 匹配是否是白名单
     *
     * @param ip
     * @return
     */
    private boolean isMatchWhiteList(String ip) {
        if (innerIpAddress == null || 0 == innerIpAddress.length) {
            log.debug("白名单为空，使用默认白名单地址：{}", INNER_IP);
            return INNER_IP.stream().anyMatch(item -> ip.startsWith(item));
        } else {
            List<String> list = Arrays.asList(innerIpAddress);
            log.debug("白名单不为空，值：{}", list);
            return list.stream().anyMatch(item -> ip.startsWith(item));
        }
    }

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
     * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
     * <p>
     * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
     * <p>
     * 用户真实IP为： 192.168.1.110
     *
     * @param request
     * @return
     */
    private String getIpAddress(ServerHttpRequest request) {
        HttpHeaders headers = request.getHeaders();
        String ip = headers.getFirst("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = headers.getFirst("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = headers.getFirst("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = headers.getFirst("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddress().getAddress().getHostAddress();
        }
        return ip;
    }


    private Mono<Void> forbidden(ServerHttpResponse response, CommonResult commonResult) {
        byte[] data = JacksonUtil.toJsonStringNoException(commonResult).getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}